﻿using Kinlo.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Services.Context;
using UIWindows.Tools.Helper;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;
using XingLucifer.IBase.Models.PLCInteraktion;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClassAttribute(TaskTypes.注液数据获取)]
    public class InjectionData : ServierBase
    {
        public InjectionData(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig,
            UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic, MesParameterStatic mesParameterStatic)
            : base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic, mesParameterStatic)
        {

        }
        public override Task Handle(DataContext context)
        {
            if (!ClearSignal(context)) { return Task.CompletedTask; }
            var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号).Communication as OmronCIP;
            try
            {
                DateTime weighing_time = DateTime.Now;
                var erinnerungen = ReadErinnerungen2(plc, context.Address_Struct, context.Struct_Length, _systemConfig.IAddress.Erinnerungen_AfterWeighing, context.AddressingMethod);
                if (erinnerungen.Item1)
                {
                    $"==>>{context.TaskType}<<==\r\n收到启动信号，没收到电池记忆，请联系电气工程师！！！".MessageDialogs(MessageLevelType.错误, false, Enums.PopUpTypes.Global);
                    return base.Handle(context);
                }
                RunLog($"记忆ID：{string.Join(";", erinnerungen.Item2.Select(x => x.SnowflakeId))}");

                for( int b = 0;b < erinnerungen.Item2.Count;b++)
                {
                    var battery = erinnerungen.Item2[b];
                    if(battery.SnowflakeId==0) { continue; }
                    DateTime dateTime = DateTime.Now;
                    ProductionData? entity = _temporaryStatic.EntityCache.FirstOrDefault(x => x.SnowflakeId == battery.SnowflakeId);
                    if (entity == null)
                    {
                        RunLog($"-[{battery.Index}] 实体缓存查询不到==>[{battery.SnowflakeId}]，转到数据库查询");
                        entity = dateTime.GetEntity(context.TaskType, battery.SnowflakeId, DBSuffix);
                    }
                    else
                    {
                        ProductionData.Meta.TableName = entity.Items["TableName"].ToString();
                    }
                    if (entity == null)
                    {
                        RunLog($"-[{battery.Index}] 数据库找不到ID为：{battery.SnowflakeId}");
                        WriteResult("", ResultTypes.数据库找不到电池, plc, battery.Address_Struct, context);
                        continue;
                    }

                    BatteryLiquidInjectionDataModel injectionDataModel = new BatteryLiquidInjectionDataModel();
                    plc.ReadClass($"PC_InjectionDataS[{b}]", injectionDataModel);
                    RunLog($"-[{battery.Index} 注液数据【{entity.BarCode}】==>>{System.Text.Json.JsonSerializer.Serialize(injectionDataModel, GlobalStatic.Options)}");
                   
                    #region 实体赋值
                    entity.LeakVacuum = injectionDataModel.LeakVacuum;
                    entity.LeakResult = injectionDataModel.VcheckResult == 1 ? ResultTypes.合格 : ResultTypes.测漏NG;
                    entity.RowNo = (byte)injectionDataModel.RowNo;
                    entity.ColunmNo = (byte)injectionDataModel.ColunmNo;
                    entity.InjectionPumpNo = (byte)injectionDataModel.InjectionPumpNo;
                    entity.CylinderNo = (byte)injectionDataModel.CylinderNo;
                    entity.LayerNumber = (byte)injectionDataModel.LayerNumber;
                    entity.InjectionTime = injectionDataModel.InjectionTime;
                    entity.CycleTime = injectionDataModel.CycleTime;
                    entity.FillingCup = (byte)injectionDataModel.InjectionNozzle;
                    entity.CycleNumber = (byte)injectionDataModel.CycleNumber;
                    entity.InjBeforeVacuum = injectionDataModel.InjBeforeVacuum;
                    entity.InjAfterVacuum = injectionDataModel.InjAfterVacuum;
                    entity.InjPressure = injectionDataModel.InjPressure;
                    // entity.CyclicPressurizationValue = CyclicPressurizationValue;
                    //entity.CirculatingVacuumValue = CirculatingVacuumValue;
                    entity.StationNo = Encoding.ASCII.GetString(new byte[] { (byte)(64 + injectionDataModel.InjectionStationNo) });
                    //  entity.StationNo = injectionDataModel.InjectionStationNo.ToString();
                    byte[] cupByte = injectionDataModel.CupCode;
                    for (int i = 1; i < 12; i = i + 2)
                    {
                        byte t = cupByte[i - 1];
                        cupByte[i - 1] = cupByte[i];
                        cupByte[i] = t;
                    }
                    entity.CupCode = Encoding.ASCII.GetString(injectionDataModel.CupCode);

                    byte[] palletByte = injectionDataModel.TrayCode;
                    for (int i = 1; i < 12; i = i + 2)
                    {
                        byte t = palletByte[i - 1];
                        palletByte[i - 1] = palletByte[i];
                        palletByte[i] = t;
                    }
                    entity.TrayCode = Encoding.ASCII.GetString(injectionDataModel.TrayCode);
                    RunLog($"-[{entity.BarCode}] 电池数据==>>{System.Text.Json.JsonSerializer.Serialize(entity, GlobalStatic.Options)}");
                    #endregion

                    #region 真空真压等设定值获取
                    ProcessDataModel processData = new ProcessDataModel();
                    plc.ReadClass<ProcessDataModel>($"PC_ProcessData", processData);
                    entity.CirculatingVacuumDuration = processData.PreCycleVacuumDuration;
                    entity.CirculatingVacuumValue = processData.PreCycleVacuumValue;
                    entity.FinalPositivePressureDuration = processData.FinalPositivePressureDuration;
                    entity.FinalPositivePressureValue = processData.FinalPositivePressureValue;
                    entity.InjectionTime = processData.InjectionTime;

                    RunLog($"-[{battery.Index} 真空真压工艺数据【{entity.BarCode}】==>>{System.Text.Json.JsonSerializer.Serialize(processData, GlobalStatic.Options)}");

                    #endregion

                    try
                    {
                        entity.Update();
                    }
                    catch (Exception ex)
                    {
                        RunLog($"-[{battery.Index}] 数据库保存异常：{ex}");
                        WriteCMD(1, plc, _systemConfig.IAddress.Alarm_AfterWeighing);
                        WriteResult("", ResultTypes.不合格, plc, battery.Address_Struct, context);
                    }
                }
            }
            catch (Exception ex)
            {
                RunLog($"-[取注液数据]异常：{ex}");
                WriteCMD(1, plc, _systemConfig.IAddress.Alarm_AfterWeighing);
            }
            return base.Handle(context);
        }
    }
}
